/*
 * FileName: LoginController.java
 *
 *  
 */
package com.mrc.core.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.mrc.core.base.Constant;
import com.mrc.core.model.SysUser;
import com.mrc.core.service.SysUserService;

@Controller
public class LoginController {
    @Autowired
    private SysUserService sysUserService;
    private Logger logger = Logger.getLogger(LoginController.class);

    /**
     * 登录
     * @param request
     * @param name
     * @param password
     * @return
     */
    @RequestMapping(value = "/login.do")
    public ModelAndView login(HttpServletRequest request, String name, String password) {
        ModelAndView mv = new ModelAndView();
        HttpSession session = request.getSession();
        logger.debug("name=" + name + "   pwd=" + password);
        SysUser user = sysUserService.findByMobile(name);

        //FIXME 密码MD5加密
        if (user != null && user.getPassword().equals(password)) {
            //登录成功放入session
            session.setAttribute(Constant.USER_SESSION_NAME, name);
            mv.setViewName("index");
            return mv;
        } else {
            //登录失败返回错误信息
            mv.setViewName("forward:/login.jsp");
            mv.addObject("message", "登录失败,用户名或密码错误");
            return mv;
        }
    }

    /**
     * 注销
     * @param session
     * @return
     */
    @RequestMapping("/unLogin.do")
    public String unLogin(HttpSession session) {
        session.invalidate();
        return "forward:/login.jsp";
    }

}
